#!/usr/bin/env node

const { spawn } = require('child_process');
const path = require('path');
const chokidar = require('chokidar');

/**
 * 渲染进程监听脚本
 * 专门用于监听渲染进程源码变化并触发重新构建
 */

const projectRoot = path.resolve(__dirname, '..');
const rendererDir = path.join(projectRoot, 'renderer');
const rendererSrcDir = path.join(rendererDir, 'src');

let buildProcess = null;
let isBuilding = false;
let pendingBuild = false;

/**
 * 执行构建
 */
function build() {
  if (isBuilding) {
    pendingBuild = true;
    return;
  }

  isBuilding = true;
  console.log('🔨 开始构建渲染进程...');

  buildProcess = spawn('npm', ['run', 'build'], {
    cwd: rendererDir,
    stdio: 'inherit',
    shell: true
  });

  buildProcess.on('close', (code) => {
    isBuilding = false;
    buildProcess = null;

    if (code === 0) {
      console.log('✅ 渲染进程构建完成');
    } else {
      console.error(`❌ 渲染进程构建失败，退出代码: ${code}`);
    }

    // 如果有待处理的构建请求，立即执行
    if (pendingBuild) {
      pendingBuild = false;
      setTimeout(build, 500); // 延迟一点时间避免频繁构建
    }
  });

  buildProcess.on('error', (error) => {
    console.error('❌ 构建进程错误:', error);
    isBuilding = false;
    buildProcess = null;
  });
}

/**
 * 监听渲染进程源码变化
 */
function watchRenderer() {
  console.log('👀 监听渲染进程源码变化...');
  console.log(`📁 监听目录: ${rendererSrcDir}`);

  const watcher = chokidar.watch([
    path.join(rendererSrcDir, '**', '*.tsx'),
    path.join(rendererSrcDir, '**', '*.ts'),
    path.join(rendererSrcDir, '**', '*.css'),
    path.join(rendererSrcDir, '**', '*.scss'),
    path.join(rendererSrcDir, '**', '*.less'),
    path.join(rendererDir, 'index.html'),
    path.join(rendererDir, 'vite.config.ts'),
    path.join(rendererDir, 'package.json')
  ], {
    ignored: [
      /node_modules/,
      /\.git/,
      /dist/,
      /\.DS_Store/
    ],
    persistent: true,
    ignoreInitial: true
  });

  watcher.on('change', (filePath) => {
    const relativePath = path.relative(projectRoot, filePath);
    console.log(`📝 文件变化: ${relativePath}`);
    build();
  });

  watcher.on('add', (filePath) => {
    const relativePath = path.relative(projectRoot, filePath);
    console.log(`➕ 新增文件: ${relativePath}`);
    build();
  });

  watcher.on('unlink', (filePath) => {
    const relativePath = path.relative(projectRoot, filePath);
    console.log(`🗑️ 删除文件: ${relativePath}`);
    build();
  });

  watcher.on('error', (error) => {
    console.error('❌ 文件监听错误:', error);
  });

  watcher.on('ready', () => {
    console.log('✅ 文件监听器就绪');
    // 执行初始构建
    build();
  });

  return watcher;
}

/**
 * 清理资源
 */
function cleanup() {
  console.log('🧹 清理资源...');
  
  if (buildProcess) {
    buildProcess.kill();
  }
  
  process.exit(0);
}

/**
 * 主函数
 */
function main() {
  console.log('🎯 启动渲染进程监听器...');
  console.log(`📁 项目根目录: ${projectRoot}`);
  
  // 启动监听
  const watcher = watchRenderer();
  
  // 处理进程退出
  process.on('SIGINT', cleanup);
  process.on('SIGTERM', cleanup);
  process.on('exit', cleanup);
}

// 启动监听器
main();